package com.tierstall.client.view.content;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;

import com.google.gwt.cell.client.ButtonCell;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.DatePickerCell;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.SelectionCell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.SimplePager.TextLocation;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.gwt.view.client.SelectionModel;
import com.tierstall.client.presenter.SearchResultPresenter;
import com.tierstall.client.presenter.UserMGMTPresenter;
import com.tierstall.client.view.content.CV_showUsers.Binder;
import com.tierstall.client.view.content.CV_showUsers.CwConstants;
import com.tierstall.client.view.main.ContentWidget;
import com.tierstall.shared.Logger;
import com.tierstall.shared.Page;
import com.tierstall.shared.TierDTO;
import com.tierstall.shared.UserDTO;
import com.tierstall.shared.UserType;

public class CV_searchResult extends ContentWidget {

//	private static CV_searchResultUiBinder uiBinder = GWT
//			.create(CV_searchResultUiBinder.class);
//
//	interface CV_searchResultUiBinder extends UiBinder<Widget, CV_searchResult> {
//	}
	interface Binder extends UiBinder<Widget, CV_searchResult> {
	}
	
	public interface Display{
		public void updateTier(TierDTO tier);
		public void editTier(TierDTO tier);
	}
	
	// Presenter
	private SearchResultPresenter presenter;
	
	private ListDataProvider<TierDTO> dataProvider;

	public void setPresenter(SearchResultPresenter presenter) {
		this.presenter = presenter;
	}
	
	public ListDataProvider<TierDTO> getListDataProvider() {
		return dataProvider;
	}

	public CV_searchResult() {
		super("Suchergebnis", "Gefilterte Anzeige der Versuchstiere", false, UserType.VIEWER, Page.SEARCH_RESULT);
		dataProvider = new ListDataProvider<TierDTO>();
		cellTable = new CellTable<TierDTO>();
		pager = new SimplePager();
//		setWidget(uiBinder.createAndBindUi(this));
	}

	/**
	 * The main CellTable.
	 */
	@UiField(provided = true)
	CellTable<TierDTO> cellTable;

	/**
	 * The pager used to change the range of data.
	 */
	@UiField(provided = true)
	SimplePager pager;

	/**
	 * Initialize this example.
	 */
	@Override
	public Widget onInitialize() {
		// Create the UiBinder.
		Binder uiBinder = GWT.create(Binder.class);
		if (uiBinder == null)
			Logger.CLIENT_INFO("it is null! :o");
		Widget widget = uiBinder.createAndBindUi(this);
		return widget;
	}
	
	public void refresh(ArrayList<TierDTO> userList){
		
	}

	public void initCellTable(ArrayList<TierDTO> userList) {
		// Create a CellTable.
		// Set a key provider that provides a unique key for each contact. If
		// key is
		// used to identify contacts when fields (such as the name and address)
		// change.
		if (userList == null)
			userList = new ArrayList<TierDTO>();
//		userList.add(new TierDTO("123", "username", "password", UserType.ADMIN, "firstname", "lastname", "email", "department"));
//		userList.add(new TierDTO("234", "username2", "password2", UserType.ADMIN, "firstname2", "lastname2", "email2", "department2"));
//		dataProvider.setList(userList);
		cellTable = new CellTable<TierDTO>(TierDTO.KEY_PROVIDER);
		cellTable.setWidth("100%", true);

		// Attach a column sort handler to the ListDataProvider to sort the
		// list.
		ListHandler<TierDTO> sortHandler = new ListHandler<TierDTO>(dataProvider.getList());
		cellTable.addColumnSortHandler(sortHandler);

		// Create a Pager to control the table.
		SimplePager.Resources pagerResources = GWT
				.create(SimplePager.Resources.class);
		pager = new SimplePager(TextLocation.CENTER, pagerResources, false, 0,
				true);
		pager.setDisplay(cellTable);

		// Add a selection model so we can select cells.
		final SelectionModel<TierDTO> selectionModel = new MultiSelectionModel<TierDTO>(
				TierDTO.KEY_PROVIDER);
		cellTable.setSelectionModel(selectionModel,
				DefaultSelectionEventManager.<TierDTO> createCheckboxManager());

		// Initialize the columns.
		initTableColumns(selectionModel, sortHandler);
		Logger.CLIENT_INFO("Celltable initialized");

		// Add the CellList to the adapter in the database.
		// CViewShowUsersPresenter.get().addDataDisplay(cellTable);
		// presenter.setCellTable(cellTable);
	}

	public HasData<TierDTO> getDataProvider() {
		return cellTable;
	}
	
	/**
	 * Add the columns to the table.
	 */
	private void initTableColumns(final SelectionModel<TierDTO> selectionModel,
			ListHandler<TierDTO> sortHandler) {
		// Checkbox column. This table will uses a checkbox column for
		// selection.
		// Alternatively, you can call cellTable.setSelectionEnabled(true) to
		// enable
		// mouse selection.
		Column<TierDTO, Boolean> checkColumn = new Column<TierDTO, Boolean>(
				new CheckboxCell(true, false)) {
			@Override
			public Boolean getValue(TierDTO object) {
				// Get the value from the selection model.
				return selectionModel.isSelected(object);
			}
		};
		cellTable.addColumn(checkColumn,
				SafeHtmlUtils.fromSafeConstant("<br/>"));
		cellTable.setColumnWidth(checkColumn, 40, Unit.PX);

		// edit TierData
		Column<TierDTO, String> editDataColumn = new Column<TierDTO, String>(
				new ButtonCell()) {
					@Override
					public String getValue(TierDTO object) {
						
						return "Edit Tier";
					}
			
		};
		cellTable.addColumn(editDataColumn, "Edit");
		editDataColumn.setFieldUpdater(new FieldUpdater<TierDTO, String>() {
			  @Override
			  public void update(int index, TierDTO object, String value) {
			    presenter.editTier(object);
			  }
			});
		
		cellTable.setColumnWidth(editDataColumn, 20, Unit.PCT);
		
		// internal id.
		Column<TierDTO, String> internalIdColumn = new Column<TierDTO, String>(
				new EditTextCell()) {
			@Override
			public String getValue(TierDTO object) {
				return object.getInternal_id();
			}
		};
		internalIdColumn.setSortable(true);
		
		sortHandler.setComparator(internalIdColumn, new Comparator<TierDTO>() {
			public int compare(TierDTO o1, TierDTO o2) {
				return (o1.getInternal_id()).compareTo(o2.getInternal_id());
			}
		});
		
		cellTable.addColumn(internalIdColumn, "Int. ID");
		internalIdColumn.setFieldUpdater(new FieldUpdater<TierDTO, String>() {
			public void update(int index, TierDTO object, String value) {
				// Called when the user changes the value.
				object.setInternal_id(value);
				// CViewShowUsersPresenter.get().refreshDisplays();
				presenter.updateTier(object);
			}
		});
		cellTable.setColumnWidth(internalIdColumn, 20, Unit.PCT);
		
		// internal number.
		Column<TierDTO, String> internalNrColumn = new Column<TierDTO, String>(
				new EditTextCell()) {
			@Override
			public String getValue(TierDTO object) {
				return ""+object.getInternal_number();
			}
		};
		internalNrColumn.setSortable(true);
		
		sortHandler.setComparator(internalNrColumn, new Comparator<TierDTO>() {
			public int compare(TierDTO o1, TierDTO o2) {
				return (o1.getInternal_number()+"").compareTo(o2.getInternal_number()+"");
			}
		});
		
		cellTable.addColumn(internalNrColumn, "Int. Nr.");
		internalNrColumn.setFieldUpdater(new FieldUpdater<TierDTO, String>() {
			public void update(int index, TierDTO object, String value) {
				// Called when the user changes the value.
				object.setInternal_number(Integer.parseInt(value));
				// CViewShowUsersPresenter.get().refreshDisplays();
				presenter.updateTier(object);
			}
		});
		cellTable.setColumnWidth(internalNrColumn, 20, Unit.PCT);
		
		// entry date.
		DateTimeFormat dateFormat = DateTimeFormat.getFormat(PredefinedFormat.DATE_MEDIUM);
		Column<TierDTO, Date> entryDateColumn = new Column<TierDTO, Date>(
				new DatePickerCell(dateFormat)) {
			@Override
			public Date getValue(TierDTO object) {
				return object.getEntry();
			}
		};
		entryDateColumn.setSortable(true);
		
		sortHandler.setComparator(entryDateColumn, new Comparator<TierDTO>() {
			public int compare(TierDTO o1, TierDTO o2) {
				return (o1.getEntry()).compareTo(o2.getEntry());
			}
		});
		
		cellTable.addColumn(entryDateColumn, "Eingangsdatum");
		entryDateColumn.setFieldUpdater(new FieldUpdater<TierDTO, Date>() {
			public void update(int index, TierDTO object, Date value) {
				// Called when the user changes the value.
				object.setEntry(value);
				// CViewShowUsersPresenter.get().refreshDisplays();
				presenter.updateTier(object);
			}
		});
		cellTable.setColumnWidth(entryDateColumn, 20, Unit.PCT);
		

//		// First name.
//		Column<UserDTO, String> firstNameColumn = new Column<UserDTO, String>(
//				new EditTextCell()) {
//			@Override
//			public String getValue(UserDTO object) {
//				return object.getFirstname();
//			}
//		};
//		firstNameColumn.setSortable(true);
//		sortHandler.setComparator(firstNameColumn, new Comparator<UserDTO>() {
//			public int compare(UserDTO o1, UserDTO o2) {
//				return o1.getFirstname().compareTo(o2.getFirstname());
//			}
//		});
//		cellTable.addColumn(firstNameColumn,
//				constants.cwCellTableColumnFirstName());
//		firstNameColumn.setFieldUpdater(new FieldUpdater<UserDTO, String>() {
//			public void update(int index, UserDTO object, String value) {
//				// Called when the user changes the value.
//				object.setFirstname(value);
//				// CViewShowUsersPresenter.get().refreshDisplays();
//				presenter.updateUser(object);
//			}
//		});
//		cellTable.setColumnWidth(firstNameColumn, 20, Unit.PCT);
//
//		// Last name.
//		Column<UserDTO, String> lastNameColumn = new Column<UserDTO, String>(
//				new EditTextCell()) {
//			@Override
//			public String getValue(UserDTO object) {
//				return object.getLastname();
//			}
//		};
//		lastNameColumn.setSortable(true);
//		sortHandler.setComparator(lastNameColumn, new Comparator<UserDTO>() {
//			public int compare(UserDTO o1, UserDTO o2) {
//				return o1.getLastname().compareTo(o2.getLastname());
//			}
//		});
//		cellTable.addColumn(lastNameColumn,
//				constants.cwCellTableColumnLastName());
//		lastNameColumn.setFieldUpdater(new FieldUpdater<UserDTO, String>() {
//			public void update(int index, UserDTO object, String value) {
//				// Called when the user changes the value.
//				object.setLastname(value);
//				// CViewShowUsersPresenter.get().refreshDisplays();
//				presenter.updateUser(object);
//			}
//		});
//		cellTable.setColumnWidth(lastNameColumn, 20, Unit.PCT);
//
//		// Category.
//		// final Category[] categories =
//		// CViewShowUsersPresenter.get().queryCategories();
//		// List<String> categoryNames = new ArrayList<String>();
//		// for (Category category : categories) {
//		// categoryNames.add(category.getDisplayName());
//		// }
//		ArrayList<String> userTypes = new ArrayList<String>();
//		for (int i = 0; i < UserType.values().length; i++)
//			userTypes.add(UserType.values()[i].type());
//		SelectionCell categoryCell = new SelectionCell(userTypes);
//		Column<UserDTO, String> categoryColumn = new Column<UserDTO, String>(
//				categoryCell) {
//			@Override
//			public String getValue(UserDTO object) {
//				return object.getPermission().type();
//			}
//		};
//		cellTable.addColumn(categoryColumn,
//				constants.cwCellTableColumnCategory());
//		categoryColumn.setFieldUpdater(new FieldUpdater<UserDTO, String>() {
//			public void update(int index, UserDTO object, String value) {
//				for (UserType category : UserType.values()) {
//					if (category.type().equals(value)) {
//						object.setPermission(category);
//					}
//				}
//				// CViewShowUsersPresenter.get().refreshDisplays();
//				presenter.updateUser(object);
//			}
//		});
//		cellTable.setColumnWidth(categoryColumn, 130, Unit.PX);
//
//		// department.
//		Column<UserDTO, String> departmentColumn = new Column<UserDTO, String>(
//				new EditTextCell()) {
//			@Override
//			public String getValue(UserDTO object) {
//				return object.getDepartment();
//			}
//		};
//		departmentColumn.setSortable(true);
//		sortHandler.setComparator(firstNameColumn, new Comparator<UserDTO>() {
//			public int compare(UserDTO o1, UserDTO o2) {
//				return o1.getFirstname().compareTo(o2.getFirstname());
//			}
//		});
//		cellTable.addColumn(firstNameColumn, "Arbeitskreis");
//		departmentColumn.setFieldUpdater(new FieldUpdater<UserDTO, String>() {
//			public void update(int index, UserDTO object, String value) {
//				// Called when the user changes the value.
//				object.setDepartment(value);
//				// CViewShowUsersPresenter.get().refreshDisplays();
//				presenter.updateUser(object);
//			}
//		});
//		cellTable.setColumnWidth(departmentColumn, 20, Unit.PCT);
//
//		// e-Mail-Address.
//		Column<UserDTO, String> addressColumn = new Column<UserDTO, String>(
//				new TextCell()) {
//			@Override
//			public String getValue(UserDTO object) {
//				return object.getEmail();
//			}
//		};
//		addressColumn.setSortable(true);
//		sortHandler.setComparator(addressColumn, new Comparator<UserDTO>() {
//			public int compare(UserDTO o1, UserDTO o2) {
//				return o1.getEmail().compareTo(o2.getEmail());
//			}
//		});
//		cellTable
//				.addColumn(addressColumn, constants.cwCellTableColumnAddress());
//		cellTable.setColumnWidth(addressColumn, 60, Unit.PCT);
	}

	@Override
	protected void asyncOnInitialize(final AsyncCallback<Widget> callback) {
		GWT.runAsync(CV_searchResult.class, new RunAsyncCallback() {

			public void onFailure(Throwable caught) {
				callback.onFailure(caught);
			}

			public void onSuccess() {
				callback.onSuccess(onInitialize());
			}
		});
		
	}

}
